package com.atguigu.tingshu.common.minio.config;

import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.minio.service.FileUploadService;
import com.atguigu.tingshu.common.minio.service.impl.FileUploadServiceImpl;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * minio的自动配置类
 */
@Configuration
@EnableConfigurationProperties(MinioProperties.class)//把MinioProperties这个类作为Bean对象放入容器中了
@ConditionalOnProperty(prefix = "minio",name = "enable",havingValue = "true")//判断是否开启minio
public class MinioAutoConfiguration {


    Logger logger = LoggerFactory.getLogger(MinioAutoConfiguration.class); //获取当前类的日志信息

    @Autowired
    private MinioProperties minioProperties;


    @Bean
    public FileUploadService fileUploadService(){
        return new FileUploadServiceImpl();
    }

    /**
     * 定义一个MinioClientd Bean对象
     */
    @Bean
    public MinioClient minioClient(){
        //1. 创建一个minioClient Client:客户端
        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint(minioProperties.getEndpointUrl())
                        .credentials(minioProperties.getAccessKey(), minioProperties.getSecreKey())
                        .build();
        // 2.判断桶是否存在
        try {
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {
                // 没找到,创建一个桶
                    minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                System.out.println("Bucket 'tingshu' already exists.");
            }
        }  catch (Exception e) {
            logger.error("创建桶失败",e);
            throw new GuiguException(201,"创建桶失败");
        }
        return minioClient;
    }



}
